#include "fileTree.h"

Tree::Tree()
{
    root = new struct tree[3000];
	root->name = "/root/ftp/root";
	root->iNode = 0;
	root->pNode = 0;
	root->type = 0;
	end = root;
	number = 0;
}

void Tree::_addd_(int node,string dirName)
{
	if(end = root + 2999){
		tree* buff = root + 1;
		while(buff->type != -1){
			buff = buff + 1;
		}
		buff->name = dirName;
		buff->iNode = number + 1;
		buff->pNode = node;
		buff->type = 0;
		return;
	}
	tree* buff = end + 1;
	buff->name = dirName;
	buff->iNode = end->iNode + 1;
	buff->pNode = node;
	buff->type = 0;
	end = buff;
	++number;
}

void Tree::_addf_(int node,string fileName)
{
	if(end = root + 2999){
		tree* buff = root + 1;
		while(buff->type != -1){
			buff = buff + 1;
		}
		buff->name = fileName;
		buff->iNode = number + 1;
		buff->pNode = node;
		buff->type = 1;
		return;
	}
	tree* buff = end + 1;
	buff->name = fileName;
	buff->iNode = end->iNode + 1;
	buff->pNode = node;
	buff->type = 1;
	end = buff;
	++number;
}

int Tree::_list_(int node,string * str)
{
	int i = 0;
	tree* buff = root;
	while(buff != end + 1){
		if(buff->pNode == node){
			str[i] = buff->name;
			++i;
		}
		buff = buff + 1;
	}
	return i;
}

void Tree::_dele_(int node,string fileName)
{
	tree* buff = root;
	if(fileName != " "){
		while(buff->name != fileName || buff->pNode != node){
			buff = buff + 1;
		}
	}
	else{
		while(buff->pNode != node){
			buff = buff + 1;
		}
	}

	if(buff->type == 1){
		buff->iNode = -1;
		buff->pNode = -1;
		buff->type = -1;
		buff->name = "";
		return;
	}

	int temp = buff->iNode;

	while(buff != end + 1){
		_dele_(temp);
	}
}

int Tree::_getd_(int node,string dirName)
{
	tree* buff = root;
	while(buff->name != dirName || buff->pNode != node && buff != end){
		buff = buff + 1;
	}

	if(buff->type = 1){
		return -1;
	}

	return buff->iNode;
}

Tree::~Tree()
{
	delete [] root;
	root = NULL;
	end = NULL;
}
